import { defineStore } from 'pinia'
import { post, get, put, API_PATHS, setAuthToken, removeAuthToken } from '@/utils/api'

/**
 * 用户信息接口
 * @description 定义用户的基本信息结构
 */
export interface User {
    id: string
    username: string
    nickname: string
    email: string
    avatar: string
    role: 'admin' | 'user' | 'guest'
    permissions: string[]
    createTime: string
    lastLoginTime: string
}

/**
 * 认证状态接口
 * @description 定义用户认证相关的状态信息
 */
export interface AuthState {
    token: string | null
    refreshToken: string | null
    isAuthenticated: boolean
    isAdmin: boolean
}

/**
 * 用户设置接口
 * @description 定义用户的个性化设置选项
 */
export interface UserSettings {
    theme: 'light' | 'dark' | 'auto'
    language: 'zh-CN' | 'en-US'
    notifications: {
        email: boolean
        browser: boolean
    }
    privacy: {
        showEmail: boolean
        showLastLogin: boolean
    }
}

/**
 * 用户状态管理Store
 * @description 管理用户相关的所有状态，包括认证、信息、设置等
 */
export const useUserStore = defineStore('user', {
    state: () => ({
        // 用户信息
        user: null as User | null,

        // 认证状态
        auth: {
            token: null,
            refreshToken: null,
            isAuthenticated: false,
            isAdmin: false
        } as AuthState,

        // 用户设置
        settings: {
            theme: 'auto',
            language: 'zh-CN',
            notifications: {
                email: true,
                browser: true
            },
            privacy: {
                showEmail: false,
                showLastLogin: true
            }
        } as UserSettings,

        // 加载状态
        loading: false,

        // 错误信息
        error: null as string | null
    }),

    getters: {
        /**
         * 获取用户信息
         * @description 返回当前用户的基本信息
         * @returns {User | null} 用户信息对象或null
         */
        getUser: (state) => state.user,

        /**
         * 获取认证状态
         * @description 返回用户的认证状态信息
         * @returns {AuthState} 认证状态对象
         */
        getAuthState: (state) => state.auth,

        /**
         * 检查是否已登录
         * @description 判断用户是否已经登录
         * @returns {boolean} 是否已登录
         */
        isLoggedIn: (state) => state.auth.isAuthenticated && state.auth.token !== null,

        /**
         * 检查是否为管理员
         * @description 判断当前用户是否具有管理员权限
         * @returns {boolean} 是否为管理员
         */
        isAdmin: (state) => state.auth.isAdmin,

        /**
         * 获取用户权限
         * @description 返回当前用户的所有权限列表
         * @returns {string[]} 权限数组
         */
        getUserPermissions: (state) => state.user?.permissions || [],

        /**
         * 检查是否有特定权限
         * @description 判断用户是否拥有指定的权限
         * @param {string} permission 权限名称
         * @returns {boolean} 是否拥有该权限
         */
        hasPermission: (state) => (permission: string) => {
            return state.user?.permissions.includes(permission) || false
        },

        /**
         * 获取用户设置
         * @description 返回用户的个性化设置
         * @returns {UserSettings} 用户设置对象
         */
        getUserSettings: (state) => state.settings,

        /**
         * 获取当前主题
         * @description 返回用户当前设置的主题
         * @returns {'light' | 'dark' | 'auto'} 主题类型
         */
        getCurrentTheme: (state) => state.settings.theme
    },

    actions: {
        /**
         * 用户登录
         * @description 处理用户登录逻辑，包括API调用、状态更新和本地存储
         * @param {Object} credentials 登录凭据
         * @param {string} credentials.username 用户名
         * @param {string} credentials.password 密码
         * @returns {Promise<{success: boolean, user?: User, error?: string}>} 登录结果
         */
        async login(credentials: { username: string; password: string }) {
            this.loading = true
            this.error = null

            try {
                const response = await post(API_PATHS.AUTH.LOGIN, credentials)

                if (response.success && response.data) {
                    const { token, refreshToken, user } = response.data

                    // 更新认证状态
                    this.auth.token = token
                    this.auth.refreshToken = refreshToken
                    this.auth.isAuthenticated = true
                    this.auth.isAdmin = user.role === 'admin'

                    // 更新用户信息
                    this.user = user

                    // 保存到本地存储
                    setAuthToken(token)
                    localStorage.setItem('refreshToken', refreshToken)
                    localStorage.setItem('user', JSON.stringify(user))

                    return { success: true, user }
                } else {
                    this.error = response.error || '登录失败'
                    return { success: false, error: this.error }
                }
            } catch (error) {
                this.error = error instanceof Error ? error.message : '登录失败'
                return { success: false, error: this.error }
            } finally {
                this.loading = false
            }
        },

        /**
         * 用户注册
         * @description 处理用户注册逻辑
         * @param {Object} userData 用户注册数据
         * @param {string} userData.username 用户名
         * @param {string} userData.email 邮箱
         * @param {string} userData.password 密码
         * @param {string} userData.nickname 昵称
         * @returns {Promise<{success: boolean, user?: User, error?: string}>} 注册结果
         */
        async register(userData: {
            username: string
            email: string
            password: string
            nickname: string
        }) {
            this.loading = true
            this.error = null

            try {
                const response = await post(API_PATHS.AUTH.REGISTER, userData)

                if (response.success && response.data) {
                    return { success: true, user: response.data.user }
                } else {
                    this.error = response.error || '注册失败'
                    return { success: false, error: this.error }
                }
            } catch (error) {
                this.error = error instanceof Error ? error.message : '注册失败'
                return { success: false, error: this.error }
            } finally {
                this.loading = false
            }
        },

        /**
         * 用户登出
         * @description 处理用户登出逻辑，清除认证状态和本地存储
         */
        async logout() {
            try {
                if (this.auth.token) {
                    await post(API_PATHS.AUTH.LOGOUT, {}, { withAuth: true })
                }
            } catch (error) {
                console.error('登出API调用失败:', error)
            } finally {
                // 清除本地状态
                this.auth.token = null
                this.auth.refreshToken = null
                this.auth.isAuthenticated = false
                this.auth.isAdmin = false
                this.user = null

                // 清除本地存储
                removeAuthToken()
                localStorage.removeItem('refreshToken')
                localStorage.removeItem('user')
            }
        },

        /**
         * 刷新用户信息
         * @description 从服务器获取最新的用户信息
         */
        async refreshUserInfo() {
            if (!this.auth.token) return

            try {
                const response = await get(API_PATHS.USER.PROFILE, { withAuth: true })

                if (response.success && response.data) {
                    this.user = response.data
                }
            } catch (error) {
                console.error('刷新用户信息失败:', error)
            }
        },

        /**
         * 更新用户设置
         * @description 更新用户的个性化设置并同步到服务器
         * @param {Partial<UserSettings>} newSettings 新的设置选项
         */
        async updateSettings(newSettings: Partial<UserSettings>) {
            this.settings = { ...this.settings, ...newSettings }

            // 保存到本地存储
            localStorage.setItem('userSettings', JSON.stringify(this.settings))

            if (this.auth.token) {
                try {
                    await put(API_PATHS.USER.UPDATE_SETTINGS, newSettings, { withAuth: true })
                } catch (error) {
                    console.error('更新设置失败:', error)
                }
            }
        },

        /**
         * 初始化用户状态
         * @description 从本地存储恢复用户状态，用于页面刷新后的状态恢复
         */
        async initializeUserState() {
            // 从本地存储恢复状态
            const token = localStorage.getItem('token')
            const refreshToken = localStorage.getItem('refreshToken')
            const userData = localStorage.getItem('user')
            const settingsData = localStorage.getItem('userSettings')

            if (token && userData) {
                this.auth.token = token
                this.auth.refreshToken = refreshToken
                this.auth.isAuthenticated = true

                const user = JSON.parse(userData)
                this.user = user
                this.auth.isAdmin = user.role === 'admin'
            }

            if (settingsData) {
                this.settings = { ...this.settings, ...JSON.parse(settingsData) }
            }
        },

        /**
         * 刷新Token
         * @description 使用refreshToken获取新的accessToken
         * @returns {Promise<boolean>} 刷新是否成功
         */
        async refreshToken() {
            if (!this.auth.refreshToken) return false

            try {
                const response = await post(API_PATHS.AUTH.REFRESH, {
                    refreshToken: this.auth.refreshToken
                })

                if (response.success && response.data) {
                    const { token, refreshToken } = response.data
                    this.auth.token = token
                    this.auth.refreshToken = refreshToken
                    setAuthToken(token)
                    localStorage.setItem('refreshToken', refreshToken)
                    return true
                }
            } catch (error) {
                console.error('刷新Token失败:', error)
            }

            // 刷新失败，清除认证状态
            await this.logout()
            return false
        }
    }
})
